package org.mosquitos.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import net.jxta.endpoint.EndpointAddress;
import net.jxta.endpoint.EndpointService;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.Messenger;
import net.jxta.endpoint.StringMessageElement;

public class SendService implements Runnable {
	private EndpointService es;
	private Map<String,Object> userList;
	private String name;
	
	public SendService(EndpointService es,Map<String,Object> userList,String name){
		this.userList = userList;
		this.es = es;
		this.name = name;
	}
	
	public void run(){
        while(true){
        	System.out.println("to who ?:");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            
            String key=null;
			try {
				key = br.readLine();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
            if(userList.containsKey(key)){
				System.out.println("what ?:");
				BufferedReader br_ = new BufferedReader(new InputStreamReader(System.in));
				String content=null;
				try {
					content = br_.readLine();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				Messenger directMessenger = es.getMessenger((EndpointAddress)userList.get(key), null);
	        	
	        	Message chat = new Message();
	        	content = "["+name+"]:"+content;
	        	chat.addMessageElement(new StringMessageElement("Chat", content, null));
	        	
	        	try {
					directMessenger.sendMessage(chat,"chatService",null);
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println("msg has been send");
            }else{
            	System.out.println("can not find :"+key);
            }
        }
	}
}
